package com.eshipenet.shipnet.shiprpc.grpc;

import com.eshipenet.shipnet.ship.FindAllResult;
import com.eshipenet.shipnet.ship.grpc.*;
import com.eshipenet.shipnet.shiprpc.service.ShipGovernorService;
import com.eshipenet.shipnet.shiprpc.util.GetJObjectUtil;
import com.eshipenet.shipnet.shiprpc.util.TimestampToDate;
import com.google.protobuf.Struct;
import com.google.protobuf.Timestamp;
import com.google.protobuf.util.Timestamps;
import io.grpc.stub.StreamObserver;
import org.json4s.JsonAST;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.Option;
import scala.collection.immutable.List;
import squirrel.JSONQuery;

import java.util.ArrayList;
import java.util.Date;

public class ShipGovernorRepoGrpcImpl extends ShipGovernorRepoGrpc.ShipGovernorRepoImplBase {
    private Logger logger = LoggerFactory.getLogger("ShipGovernorRepoGrpcImpl");
    private ShipGovernorService service;
    public ShipGovernorRepoGrpcImpl(ShipGovernorService service) {
        this.service = service;
    }


    /**
     * 查询列表
     *
     * @param req
     * @param responseObserver
     */
    public void findAll(ShipGovernorFindAllRequest req, StreamObserver<ShipGovernorFindAllReply> responseObserver) {

        try {
            logger.info("ShipGovernorRepoGrpcImpl.findAll.Filter    {}",req.getFilter());
            ShipGovernorFindAllReply reply = findAllInner(req);
            responseObserver.onNext(reply);
            responseObserver.onCompleted();

        } catch (Exception e) {
                responseObserver.onError(e);
        }

    }


    /**
     * 创建
     *
     * @param req
     * @param responseObserver
     */
    public void createOne(ShipGovernorCreateOneRequest req, StreamObserver<ShipGovernorCreateOneReply> responseObserver) {
        try {
            logger.info("ShipGovernorRepoGrpcImpl.createOne.data   {}",req.getData());
            ShipGovernorCreateOneReply reply = createOneInner(req);
            responseObserver.onNext(reply);
            responseObserver.onCompleted();

        } catch (Exception e) {
            responseObserver.onError(e);
        }

    }

    /**
     * 修改
     *
     * @param req
     * @param responseObserver
     */
    public void updateOne(ShipGovernorUpdateOneRequest req, StreamObserver<ShipGovernorUpdateOneReply> responseObserver) {
        try {
            logger.info("ShipGovernorRepoGrpcImpl.updateOne.data   {}",req.getData());
            ShipGovernorUpdateOneReply reply = updateOneInner(req);
            responseObserver.onNext(reply);
            responseObserver.onCompleted();

        } catch (Exception e) {
            responseObserver.onError(e);
        }

    }


    /**
     * 删除
     *
     * @param req
     * @param responseObserver
     */
    public void deleteOne(ShipGovernorDeleteOneRequest req, StreamObserver<ShipGovernorDeleteOneReply> responseObserver) {
        try {
            logger.info("ShipGovernorRepoGrpcImpl.deleteOne.id  {}",req.getId());
            ShipGovernorDeleteOneReply reply = deleteOneInner(req);
            responseObserver.onNext(reply);
            responseObserver.onCompleted();

        } catch (Exception e) {
            responseObserver.onError(e);
        }

    }

    public ShipGovernorFindAllReply findAllInner(ShipGovernorFindAllRequest req) {

        int limit = req.getFilter().getLimit();
        int offset = req.getFilter().getOffset();

        if (limit == 0) {
            limit = 500;

        }
        if (offset == 0) {
            offset = 1;

        }

        //查询条件
        Struct wheres = req.getFilter().getWhere();

        JsonAST.JObject jObject = GetJObjectUtil.getWhere(wheres);

        //联合查询
        java.util.List<ShipGovernorFindAllFilterInclude> in_list = req.getFilter().getIncludeList();

        ArrayList<JsonAST.JValue> arrayList = new ArrayList<>();

        for (ShipGovernorFindAllFilterInclude include : in_list) {

            JsonAST.JValue jValue = new JsonAST.JString(include.getName());

            arrayList.add(jValue);

        }
        List<JsonAST.JValue> includes_list = scala.collection.JavaConverters.asScalaIterator(arrayList.iterator()).toList();

        JsonAST.JArray jArray = new JsonAST.JArray(includes_list);

        //生成查询列表的sql
        JSONQuery jsonQuery = JSONQuery.apply(new JsonAST.JString("ShipGovernor"),
                Option.apply(jObject),
                Option.apply(new JsonAST.JString("*")),
                Option.apply(jArray),
                Option.apply(null),
                Option.apply(null));

        FindAllResult result = service.findAll(jsonQuery,limit,offset);
        //数据总数
        int totalCount = result.getTotalCount();
        //列表数据
        java.util.List list = new ArrayList<>();
        //判断是否有数据，无数据时直接返回
        if (totalCount < 1) {
            //设置分页信息
            PageInfo pageInfo = PageInfo.newBuilder()
                    .setHasNextPage(result.isHasNextPage())
                    .setHasPreviousPage(result.isHasPreviousPage())
                    .build();

            return ShipGovernorFindAllReply.newBuilder()
                    .setReq(req)
                    .addAllEdges(list)
                    .setPageInfo(pageInfo)
                    .setTotalCount(0).build();
        }

        list = result.getList();

        //设置分页信息
        PageInfo pageInfo = PageInfo.newBuilder()
                .setHasNextPage(result.isHasNextPage())
                .setHasPreviousPage(result.isHasPreviousPage())
                .setStartCursor(result.getStartCursor())
                .setEndCursor(result.getEndCursor()).build();


        return ShipGovernorFindAllReply.newBuilder()
                .setReq(req)
                .addAllEdges(list)
                .setPageInfo(pageInfo)
                .setTotalCount(totalCount).build();
    }


    public ShipGovernorCreateOneReply createOneInner(ShipGovernorCreateOneRequest req) {

        //获取当前时间
        java.sql.Timestamp createdAt = new java.sql.Timestamp(System.currentTimeMillis());
        Timestamp createdAt1 = Timestamps.fromMillis(new Date().getTime());

        Struct data = req.getData().getInfo();
        String data_str = GetJObjectUtil.getData(data);

        com.eshipenet.shipnet.ship.ShipGovernor shipGovernor =  new com.eshipenet.shipnet.ship.ShipGovernor(
                req.getData().getName(),
                req.getData().getDesc(),
                req.getData().getAvatar(),
                data_str,
                createdAt,
                createdAt,
                req.getData().getId());

        shipGovernor = service.createOne(shipGovernor);

        ShipGovernor shipGovernorBuilder = ShipGovernor.newBuilder()
                .setId(shipGovernor.getId())
                .setName(shipGovernor.getName())
                .setDesc(shipGovernor.getDescription())
                .setAvatar(shipGovernor.getAvatar())
                .setUpdatedAt(TimestampToDate.dateTotimestamp(shipGovernor.getUpdatedAt()))
                .setCreatedAt(TimestampToDate.dateTotimestamp(shipGovernor.getCreatedAt()))
                .setInfo(req.getData().getInfo())
                .build();

        return ShipGovernorCreateOneReply.newBuilder().setData(shipGovernorBuilder).setReq(req).build();


    }


    public ShipGovernorUpdateOneReply updateOneInner(ShipGovernorUpdateOneRequest req) {
        //获取当前时间
        java.sql.Timestamp updatedAt = new java.sql.Timestamp(System.currentTimeMillis());

        Struct data = req.getData().getInfo();
        String data_str = GetJObjectUtil.getData(data);
        com.eshipenet.shipnet.ship.ShipGovernor shipGovernor = new com.eshipenet.shipnet.ship.ShipGovernor(
                req.getData().getName(),
                req.getData().getDesc(),
                req.getData().getAvatar(),
                data_str,
                null,
                updatedAt,
                req.getData().getId()
        );

        shipGovernor =  service.updateOne(req.getData().getId(),shipGovernor);

        System.out.println(shipGovernor);

        ShipGovernor shipGovernorBuilder = ShipGovernor.newBuilder()
                .setId(shipGovernor.getId())
                .setName(shipGovernor.getName())
                .setDesc(shipGovernor.getDescription())
                .setAvatar(shipGovernor.getAvatar())
                .setCreatedAt(TimestampToDate.dateTotimestamp(shipGovernor.getCreatedAt()))
                .setUpdatedAt(TimestampToDate.dateTotimestamp(shipGovernor.getUpdatedAt()))
                .setInfo(GetJObjectUtil.getData(shipGovernor.getInfo()))
                .build();


        return ShipGovernorUpdateOneReply.newBuilder().setData(shipGovernorBuilder).setReq(req).build();


    }



    public ShipGovernorDeleteOneReply deleteOneInner(ShipGovernorDeleteOneRequest req) {

        com.eshipenet.shipnet.ship.ShipGovernor shipGovernor = service.deleteOne(req.getId());

        ShipGovernor shipGovernorBuilder = ShipGovernor
                .newBuilder()
                .setId(shipGovernor.getId())
                .setName(shipGovernor.getName())
                .setAvatar(shipGovernor.getAvatar())
                .setInfo(GetJObjectUtil.getData(shipGovernor.getInfo()))
                .setUpdatedAt(TimestampToDate.dateTotimestamp(shipGovernor.getUpdatedAt()))
                .setCreatedAt(TimestampToDate.dateTotimestamp(shipGovernor.getCreatedAt()))
                .setDesc(shipGovernor.getDescription())
                .build();

        return ShipGovernorDeleteOneReply.newBuilder().setData(shipGovernorBuilder).setReq(req).build();

    }

}

